package ilender.controller;

import java.util.List;
import java.util.TreeSet;

import lombok.*;

import com.google.gson.*;
import org.joda.time.*;

import ilender.annotations.*;
import ilender.dispatching.ControllerTools;
import ilender.mappers.*;
import ilender.models.*;
import ilender.util.*;
import ilender.exceptions.*;

/**
 * @see Controller
 */
@Controller("facebook")
public class FacebookController{

	/**
	 * Called after a Facebook-related action in the client-side.
	 *
	 * Used to send notifications on Facebook actions.
	 *
	 * @param request <pre>
	 * {
	 * 		href:(url of target object)
	 * }
	 * </pre>
	 */
	public static JsonElement notifyOnAction(JsonObject request,ControllerTools tools){
		String href=request.get("href").getAsString();
		String[] refParts=href.split("=")[1].split("%23");
		BaseModel model=null;
		long refId=Long.parseLong(refParts[1]);
		val userIds=new TreeSet<Long>();
		switch(refParts[0]){
			case "MItem":
				val item=tools.session.getMapper(ItemsMapper.class).find(refId);
				userIds.add(item.getFacebook_user_id());
				model=item;
				break;
			case "MOffer":
				val offer=tools.session.getMapper(OffersMapper.class).find(refId);
				userIds.add(offer.getItem().getFacebook_user_id());
				userIds.add(offer.getRequest().getFacebook_user_id());
				model=offer;
				break;
		}
		JsonArray commentsJson=null;
		for(val e : tools.fbUser.graphAPI.makeGetRequest("comments","ids",href).getAsJsonObject().entrySet()){
			commentsJson=e.getValue().getAsJsonObject().getAsJsonObject("comments").getAsJsonArray("data");
		}
		for(val comment : commentsJson){
			userIds.add(comment.getAsJsonObject().getAsJsonObject("from").get("id").getAsLong());
		}
		userIds.remove(tools.fbUser.id);
		for(val userId : userIds){
			String refName=null;
			if(model instanceof MItem){
				val item=(MItem)model;
				if(item.getFacebook_user_id()==userId){
					refName=String.format("your %s",item.getName());
				}else{
					refName=String.format("@[%s]'s %s",item.getFacebook_user_id(),item.getName());
				}
			}else if(model instanceof MOffer){
				val offer=(MOffer)model;
				if(offer.getItem().getFacebook_user_id()==userId){
					refName=String.format("@[%s]'s %s borrow from you",
							offer.getRequest().getFacebook_user_id(),
							offer.getItem().getName());
				}else if(offer.getRequest().getFacebook_user_id()==userId){
					refName=String.format("your %s borrow from @[%s]",
							offer.getItem().getName(),
							offer.getItem().getFacebook_user_id());
				}else{
					refName=String.format("@[%s]'s %s borrow from @[%s]",
							offer.getRequest().getFacebook_user_id(),
							offer.getItem().getName(),
							offer.getItem().getFacebook_user_id());
				}
			}
			tools.fbUser.graphAPI.getFBUser(userId).notification().setReference(model).setTemplate(String.format(
						"@[%s] has commented on %s",
						tools.fbUser.id,refName
						)).post();
		}

		return JsonTools.makeObject("sent_notifications_to",userIds);
	}
}
